# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root is None:
            return None
        
        q=[root]
        while q:
            size=len(q)
            last=None
            for _ in range(size):
                node=q.pop(0)
                if last:
                    last.next=node
                last=node

                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
        
        return root
